<html>
<head>
<style type="text/css">
html, body {
    width: 100%;
    height: 100%;
    margin: 0;
}
</style>
<script type="text/javascript">

function toHtmlColor(mltColor) {
    if (mltColor.length > 7) {
        var a = parseInt(mltColor.substring(1, 3), 16)
        var r = parseInt(mltColor.substring(3, 5), 16)
        var g = parseInt(mltColor.substring(5, 7), 16)
        var b = parseInt(mltColor.substring(7, 9), 16)
        return 'rgba(' + r + ',' + g + ',' + b + ',' + a/255 + ')' 
    } else {
        var r = parseInt(mltColor.substring(1, 3), 16)
        var g = parseInt(mltColor.substring(3, 5), 16)
        var b = parseInt(mltColor.substring(5, 7), 16)
        return 'rgb(' + r + ',' + g + ',' + b + ')' 
    }
}

function Filter() {
    // Create a canvas
    this.canvas = document.createElement('canvas');
    this.canvas.width = window.innerWidth;
    this.canvas.height = window.innerHeight;
    document.body.appendChild(this.canvas);
    this.context = this.canvas.getContext('2d');

    // Set the document background color.
    var color = webvfx.getStringParameter('color');
    if (!color)
        color = 'black';
    else
        color = toHtmlColor(color);
    document.body.style.backgroundColor = color;

    // Clip video to a circle in the middle of the canvas
    var radius = webvfx.getNumberParameter('radius');
    this.context.beginPath();
    this.context.arc(this.canvas.width/2, this.canvas.height/2,
                     this.hypotenuse() / 2 * radius, 0, Math.PI*2, true)
    this.context.clip();

    this.image = new Image();
}

Filter.prototype.hypotenuse = function() {
    return Math.sqrt(Math.pow(this.canvas.width, 2) + Math.pow(this.canvas.height, 2));
}

Filter.prototype.render = function(time) {
    var color = webvfx.getStringParameter('color')
    if (color && color != document.body.style.backgroundColor)
        document.body.style.backgroundColor = toHtmlColor(color);
    var radius = webvfx.getNumberParameter('radius')

    // Clear/reset the canvas
    this.canvas.width = this.canvas.width;

    this.context.beginPath();
    this.context.arc(this.canvas.width/2, this.canvas.height/2,
                     this.hypotenuse() / 2 * radius, 0, Math.PI*2, true)
    this.context.clip();

    webvfx.getImage("video").assignToHTMLImageElement(this.image);
    this.context.drawImage(this.image, 0, 0);
}

function init() {
    var filter = new Filter();
    webvfx.renderRequested.connect(filter, Filter.prototype.render);
    webvfx.imageTypeMap = { "video" : webvfx.SourceImageType };
    webvfx.readyRender(true);
}
window.addEventListener("load", init, false);
</script>
</head>
<body>
</body>
</html>
